package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.dto.YddUserDto;
import com.itheima.entity.YddUser;
import com.itheima.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ydd_user")
public class YddUSerController {

    @Autowired
    private YddUserService yddUserService;

    /**
     * 分页查询
     * @param sex
     * @param username
     * @param mobile
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public R<YddUserDto> list(Integer sex, String username, String mobile, @RequestParam Integer page, @RequestParam("limit") Integer pageSize) {
        log.info("请求数据：sex:{}, username:{}, mobile:{}, page:{}, pageSize:{}", sex, username, mobile, page, pageSize);
        YddUserDto yddUserDto = yddUserService.getList(sex, username, mobile, page, pageSize);

        return R.success(yddUserDto);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<YddUser> rowInfo(@RequestParam Integer id){
        log.info("id:{}", id);
        YddUser user = yddUserService.getById(id);
        return R.success(user);
    }

    /**
     * 修改用户信息
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    @CacheEvict(value = "indexCache", allEntries = true)
    public R<String> update(@RequestBody YddUser yddUser){
        log.info("yddUser:{}", yddUser );
        yddUserService.updateById(yddUser);
        return R.success("修改成功");
    }

    /**
     * 添加用户
     * @param yddUser
     * @return
     */
    @PostMapping("/add")
    @CacheEvict(value = "indexCache", allEntries = true)
    public R<String> add(@RequestBody YddUser yddUser){
        log.info("yddUser:{}", yddUser );
        //将页面提交的密码password进行md5加密处理
        String password = yddUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        yddUser.setPassword(password);
        yddUserService.save(yddUser);
        return R.success("添加成功");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/del")
    @CacheEvict(value = "indexCache", allEntries = true)
    public R<String> del(@RequestParam Integer id){
        log.info("id:{}", id);
        yddUserService.removeById(id);
        return R.success("删除成功");
    }
}
